package com.hello.web.service.role;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hello.common.utils.PageResponse;
import com.hello.common.utils.Response;
import com.hello.web.domain.bo.role.AddRoleBO;
import com.hello.web.domain.bo.role.DelRoleBO;
import com.hello.web.domain.bo.role.RoleQueryBO;
import com.hello.web.domain.entity.RoleDO;
import com.hello.web.domain.entity.RolePermissionDO;
import com.hello.web.domain.mapper.RoleMapper;
import com.hello.web.domain.mapper.RolePermissionMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class RoleService {

    private final RoleMapper roleMapper;
    private final RolePermissionMapper rolePermissionMapper;

    public PageResponse queryRolePageList(RoleQueryBO bo) {
        Page<RoleDO> page = new Page<>(bo.getCurrent(), bo.getSize());
        LambdaQueryWrapper<RoleDO> wrapper = new LambdaQueryWrapper<>(RoleDO.class)
                .like(StrUtil.isNotBlank(bo.getName()), RoleDO::getName, bo.getName());
        Page<RoleDO> userDOPage = roleMapper.selectPage(page, wrapper);
        return PageResponse.success(userDOPage, userDOPage.getRecords());
    }

    public Response queryRoleList() {
        return Response.success(roleMapper.selectList(null));
    }

    public Response addRole(AddRoleBO bo) {
        if (bo.getId() == null) {
            roleMapper.insert(RoleDO.builder()
                    .name(bo.getName())
                    .remark(bo.getRemark())
                    .status(bo.getStatus())
                    .build());
        }else {
            RoleDO roleDO = roleMapper.selectById(bo.getId());
            BeanUtil.copyProperties(bo, roleDO, CopyOptions.create().setIgnoreNullValue(true));
            roleMapper.updateById(roleDO);
        }
        return Response.success(roleMapper.findByName(bo.getName()));
    }

    public void deleteRole(DelRoleBO bo) {
        roleMapper.deleteById(bo.getId());
        rolePermissionMapper.delete(new LambdaQueryWrapper<RolePermissionDO>().eq(RolePermissionDO::getRoleId, bo.getId()));
    }


}
